<?php
namespace app\common\model;
use think\facade\Cache;
use think\facade\Db;

class Merch extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 好物商家详情
     * @param $user
     * @param $merch_id
     * @return array
     * @throws DeveloperException
     * @throws UserException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function thingDetail($user,$merch_id){
        $merch_id = intval($merch_id);

        //商家
        $info = self::where('id','=',$merch_id)
            ->field("id,type,title,logo,background,mobile,start_hour,end_hour,address,status,check")
            ->findOrEmpty()
            ->toArray();

        if(!$info){
            throw new UserException('无此商家');
        }
        if($info['type']!=2){
            throw new DeveloperException('接口只支持'.get_base_type(3,2).'商家');
        }
        if($info['check']!=1){
            throw new UserException('商家还在审核中');
        }
        if(!$info['status']){
            throw new UserException('商家已关闭');
        }

        Db::name('merch')->where('id','=',$merch_id)
            ->inc('views',1)
            ->inc('views_show',1)
            ->update();

        //聊天客服
        $info['chat_uid'] = MerchAdmin::getMerchAdminChatUid($merch_id);

        //背景
        $info['logo'] = manageImg($info['logo']);
        $info['background'] = manageImg($info['background']);

        //营业时间
        $info['merch_time'] = '营业时间：'.substr($info['start_hour'],0,5).'-'.substr($info['end_hour'],0,5);

        //关注人数
        $info['focus'] = UserFocus::merchFocusNum($merch_id);

        //是否关注
        $info['is_focus'] = UserFocus::isFocus($user,$merch_id);

        //标签
        $facility = Db::name('merch_facility')->where('merch_id',$merch_id)->value('facility');
        $info['tags'] = self::unSerTags($facility);

        //商家分类
        $category = CategoryMerch::getCategory($merch_id);


        $goods = Db::name('goods')
            ->where('merch_id','=',$merch_id)
            ->where('activity_type','=',1)//普通
            ->where('status','=',1)
            ->where('check','=',1)
            ->where('stock','>',0)
            ->order('merch_sort DESC,id DESC')
            ->field('id,category_merch_id,type,activity_type,title,thumb,price,vip_percent,coin_percent')
            ->select()
            ->toArray();

        foreach ($goods as &$one){
            $one['thumb'] = manageImg($one['thumb']);
            $one = Goods::showPrice($one);
        }
        unset($one);

        //分类和商品组合
        foreach ($category as &$item){
            $item['goods'] = [];
            foreach ($goods as $go){
                if($go['category_merch_id']==$item['id']){
                    array_push($item['goods'],$go);
                }
            }
        }
        unset($item);
        $info['category'] = $category;

        unset($info['status']);
        unset($info['check']);
        unset($info['start_hour']);
        unset($info['end_hour']);
        return $info;
    }

    /**
     * 团购商家详情
     * @param $merch_id
     * @return array
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function groupDetail($user,$merch_id,$longitude,$latitude){
        //商家
        $info = self::where('id','=',$merch_id)
            ->field("id,type,title,logo,background,mobile,start_hour,end_hour,address,longitude,latitude,status,check")
            ->findOrEmpty()
            ->toArray();
        if(!$info){
            throw new UserException('无此商家');
        }
        if($info['type']!=1){
            throw new DeveloperException('接口只支持'.get_base_type(3,1).'商家');
        }
        if($info['check']!=1){
            throw new UserException('商家还在审核中');
        }
        if(!$info['status']){
            throw new UserException('商家已关闭');
        }

        Db::name('merch')->where('id','=',$merch_id)
            ->inc('views',1)
            ->inc('views_show',1)
            ->update();

        //在线客服
        $info['chat_uid'] = MerchAdmin::getMerchAdminChatUid($merch_id);

        //背景
        $info['logo'] = manageImg($info['logo']);
        $info['background'] = manageImg($info['background']);

        //距离
        if($longitude && $latitude){
            $info['distance'] = '距离'.distance($latitude, $longitude, $info['latitude'], $info['longitude']).'公里';
        }else{
            $info['distance'] = $info['address'];
        }

        //营业时间
        $info['merch_time'] = '营业时间：'.substr($info['start_hour'],0,5).'-'.substr($info['end_hour'],0,5);

        //关注人数
        $info['focus'] = UserFocus::merchFocusNum($merch_id);

        //是否关注
        $info['is_focus'] = UserFocus::isFocus($user,$merch_id);

        //标签
        $facility = Db::name('merch_facility')->where('merch_id',$merch_id)->value('facility');
        $info['tags'] = self::unSerTags($facility);

        //商家分类
        $category = CategoryMerch::getCategory($merch_id);

        $goods = Db::name('goods')
            ->where('merch_id','=',$merch_id)
            ->where('activity_type','=',1)
            ->where('status','=',1)
            ->where('check','=',1)
            ->where('stock','>',0)
            ->order('merch_sort DESC,id DESC')
            ->column('id,category_merch_id,type,activity_type,title,thumb,price,vip_percent,coin_percent,use_spec,
            0 as num,unit,stock,min_buy,max_buy,all_buy','id');

        foreach ($goods as &$one){
            $one['max_buy'] = Goods::madeMaxBuy($one['max_buy'],$one['all_buy']);
            unset($one['all_buy']);
            $one['thumb'] = manageImg($one['thumb']);
            $one = Goods::showPrice($one);
        }
        unset($one);

        //如果登录了商品列表获取被选数量
        if($user){
            //购物车
            $goods_car = GoodsCar::where('merch_id','=',$merch_id)
                ->where('uid','=',$user['id'])
                ->field('id,goods_id,sku,num')
                ->order('id DESC')
                ->select()
                ->toArray();
            foreach ($goods_car as &$ca){
                //商品被选数量加
                $goods[$ca['goods_id']]['num'] += $ca['num'];
            }
        }

        //购物车数据
        $info['car'] = GoodsCar::merchCar($user,$merch_id);

        //分类和商品组合
        foreach ($category as &$item){
            $item['goods'] = [];
            foreach ($goods as $go){
                if($go['category_merch_id']==$item['id']){
                    array_push($item['goods'],$go);
                }
            }
        }
        unset($item);
        $info['category'] = $category;

        unset($info['status']);
        unset($info['check']);
        unset($info['start_hour']);
        unset($info['end_hour']);
        return $info;
    }

    /**
     * 某个商品规格
     * @param $user
     * @param $goods_id
     * @param $source
     * @return array
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function goodsSku($user,$goods_id,$source){

        //该商品已经
        $goods_car = Db::name('goods_car')
            ->where('uid','=',$user['id'])
            ->where('goods_id','=',$goods_id)
            ->where('sku','<>','')
            ->column('num','sku');

        $goods = Db::name('goods')
            ->where('id',$goods_id)
            ->field('coin_percent,vip_percent,min_buy,max_buy,all_buy')
            ->find();
        if(!$goods){
            throw new UserException('商品已下架请重新进入页面后选择');
        }

        //规格组
        $spec = Db::name('goods_spec')
            ->where('goods_id',$goods_id)
            ->order('id ASC')
            ->field('id as spec_id,title as spec_title')
            ->select()
            ->toArray();

        if($source==1){
            //安卓
            $skus = Db::name('goods_spec_option')
                ->where('goods_id',$goods_id)
                ->order('id ASC')
                ->field('spec_item_title,thumb,sku,price,stock,goods_id')
                ->select()
                ->toArray();
            foreach ($skus as &$sku){

                $item_arr = explode('+',$sku['spec_item_title']);
                foreach ($item_arr as $k=>$v){
                    $sku['attributes'][] = [
                        'key'=>$spec[$k]['spec_title'],
                        'value'=>$v
                    ];
                }

                $sku['thumb'] = manageImg($sku['thumb']);

                //如果是vip显示vip价格
                $sku['price'] += 0;
                if(UserLevel::isVip($user)){
                    $sku['price'] = Goods::getVipPrice($sku['price'],$goods['vip_percent']);
                }

                //已选规格数量
                $sku['num'] = $goods_car[$sku['sku']] ?? 0;
            }
            unset($sku);
            $arr = ['skus'=>$skus];
        }elseif($source==2){
            //IOS
            foreach ($spec as &$item){
                $item['item'] = Db::name("goods_spec_item")
                    ->where('spec_id',$item['spec_id'])
                    ->order('id ASC')
                    ->column('title');
            }
            unset($item);
            $arr['spec'] = $spec;

            //规格列表
            $spec_option = Db::name('goods_spec_option')
                ->where('goods_id',$goods_id)
                ->order('id ASC')
                ->field('spec_item_title,spec_item_id,thumb,sku,price,stock,goods_id')
                ->select()
                ->toArray();
            foreach ($spec_option as &$op){
                $op['thumb'] = manageImg($op['thumb']);

                //如果是vip显示vip价格
                $op['price'] += 0;
                if(UserLevel::isVip($user)){
                    $op['price'] = Goods::getVipPrice($op['price'],$goods['vip_percent']);
                }

                //已选数量
                $op['num'] = $goods_car[$op['sku']] ?? 0;
            }
            unset($op);
            $arr['spec_option'] = $spec_option;
        }else{
            //小程序
            $key = [];
            foreach ($spec as $item) {
                $spec_list = Db::name("goods_spec_item")
                    ->where("spec_id", $item['spec_id'])
                    ->field("title val, '' state, '{$item['spec_title']}' name")
                    ->select()
                    ->toArray();
                array_push($key, $spec_list);
            }
            $arr['key'] = $key;

            //sku_list
            $sku_list = Db::name("goods_spec_option")->where("goods_id", $goods_id)
                ->field("sku sku_id, spec_item_title attrs,stock,price, thumb image,goods_id")
                ->select()
                ->each(function ($val)use($user,$goods,$goods_car) {
                    $val['image'] = manageImg($val['image']);

                    //如果是会员显示会员价
                    $val['price'] +=0;
                    if(UserLevel::isVip($user)){
                        $val['price'] = Goods::getVipPrice($val['price'],$goods['vip_percent']);
                    }

                    //选择数量
                    $val['num'] = $goods_car[$val['sku_id']] ?? 0;

                    return $val;
                })
                ->toArray();
            $arr['sku_list'] = $sku_list;
        }

        $arr['min_buy'] = $goods['min_buy'];
        $arr['max_buy'] = Goods::madeMaxBuy($goods['max_buy'],$goods['all_buy']);
        return $arr;
    }

    /**
     * 是否是商户
     * @param $user
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function isMerch($user){
        $status = 0;
        if($user){
            $merch = self::where('uid','=',$user['id'])
                ->where('check','=',1)
                ->field('id')
                ->find();
            if($merch){
                $status = 1;
            }
        }
        return $status;
    }

    /**
     * 入驻状态
     * @param $user
     * @return array
     */
    static public function applyStatus($user){
        $arr = [
            'status'=>'',
            'msg'=>'请先登录'
        ];

        if($user){
            $merch = self::where('uid','=',$user['id'])
                ->field('id,check,reason')
                ->findOrEmpty()
                ->toArray();
            if(!$merch){
                $arr['status'] = 0;
                $arr['msg'] = '未提交';
            }else{
                if(in_array($merch['check'],[0,-1])){
                    //初审或复审中
                    $arr['status'] = 1;
                    $arr['msg'] = '您的申请已提交，请耐心等待审核！';
                }elseif ($merch['check']==1){
                    //审核通过了
                    $arr['status'] = 2;
                    $arr['msg'] = '您的入驻申请已通过';
                }else{
                    //初审驳回或者复审驳回了
                    $arr['status'] = 3;
                    $arr['msg'] = empty($merch['reason'])?'申请入驻失败，请仔细检查您的信息是否准确':('申请入驻失败，'.$merch['reason']);
                }
            }
        }
        return $arr;
    }

    /**
     * 商家入驻信息
     * @param $user
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \app\api\model\ServerException
     */
    static public function applyInfo($user){

        $merch = self::where('uid','=',$user['id'])
            ->findOrEmpty()
            ->toArray();

        //商家类型
        $type_list = get_base_type();
        foreach ($type_list as &$item){
            $item['title'] .= '商户';

            if($merch){
                $item['checked'] = $item['type']==$merch['type'] ? 1 : 0;
            }else{
                $item['checked'] = $item['type']==1 ? 1 : 0;
            }

            unset($item['color']);
        }
        unset($item);

        $arr = [
            'check'=>-3,
            'reason'=>'',
            'background'=>'',
            'business_mobile'=>'',
            'type'=>array_values($type_list),
            'last_type'=>1,
            'last_type_title'=>get_base_type(3,1).'商户',
            'title'=>'',
            'mobile'=>'',
            'pro_id'=>'',
            'pro_name'=>'',
            'city_id'=>'',
            'city_name'=>'',
            'area_id'=>'',
            'area_name'=>'',
            'address'=>'',
            'longitude'=>'',
            'latitude'=>'',
            'start_hour'=>'',
            'end_hour'=>'',
            'license'=>'',
            'logo'=>''
        ];

        //查不到商家入驻记录直接返回默认
        if(!$merch){
            return $arr;
        }

        $arr['check'] = $merch['check'];
        $arr['reason'] = in_array($merch['check'],[-2,2]) ? ('拒绝理由：'.$merch['reason']) : '';
        $arr['background'] = $merch['background']=='' ? '' :manageImg($merch['background']);

        //业务经理手机号
        if($merch['business_uid']>0){
            $business_user = UserTeamLevel::getBusiness(1,$merch['business_uid']);
            if($business_user){
                $arr['business_mobile'] = $business_user['mobile'];
            }
        }

        $arr['last_type'] = $merch['type'];
        $arr['last_type_title'] = get_base_type(3,$merch['type']).'商户';
        $arr['title'] = $merch['title'];
        $arr['mobile'] = $merch['mobile'];
        $arr['pro_id'] = $merch['pro_id'];
        $arr['city_id'] = $merch['city_id'];
        $arr['area_id'] = $merch['area_id'];
        $arr['pro_name'] = Region::getRegionName($merch['pro_id']);
        $arr['city_name'] = Region::getRegionName($merch['city_id']);
        $arr['area_name'] = Region::getRegionName($merch['area_id']);
        $arr['address'] = $merch['address'];
        $arr['longitude'] = $merch['longitude'];
        $arr['latitude'] = $merch['latitude'];
        $arr['start_hour'] = substr($merch['start_hour'],0,5);
        $arr['end_hour'] = substr($merch['end_hour'],0,5);
        $arr['license'] = $merch['license']=='' ? '' :manageImg($merch['license']);
        $arr['logo'] = $merch['logo']=='' ? '' :manageImg($merch['logo']);

        return $arr;
    }

    /**
     * 入驻申请提交
     * @param $user
     * @param $data
     * @return void
     * @throws ServerException
     * @throws UserException
     */
    static public function applySub($user,$data,$business_mobile){

        $merch = self::where('uid','=',$user['id'])
            ->field('id,check')
            ->findOrEmpty()
            ->toArray();
        if($merch && in_array($merch['check'],[0,-1])){
            throw new UserException('您已提交入驻申请，正在审核，请勿重复提交');
        }

        if($merch && $merch['check']==1){
            throw new UserException('您已成功入驻，请勿重复提交');
        }

        //业务经理
        $data['business_uid'] = 0;
        $business_mobile = reInject($business_mobile);
        if($business_mobile != ''){

            $business_name = UserTeamLevel::getBusinessLevelName();

            $business = UserTeamLevel::getBusiness(2,$business_mobile);
            if(!$business){
                throw new UserException("请检查输入的{$business_name}手机号是否有误，若不确定可不填入");
            }

            if($business_mobile == $user['mobile']){
                throw new UserException("自己不可以作为自己入驻时的{$business_name}");
            }

            $data['business_uid'] = $business['id'];
        }

        if(strlen($data['start_hour'])==5){
            $data['start_hour'] .= ':00';
        }

        if(strlen($data['end_hour'])==5){
            $data['end_hour'] .= ':00';
        }

        $data['uid'] = $user['id'];
        $data['check'] = -1;//从初审开始
        if($merch){
            $data['id'] = $merch['id'];
        }

        //验证
        $validate = new \app\common\validate\Merch();
        if(!$validate->check($data)){
            throw new UserException($validate->getError());
        }

        if($merch){
            $save = self::update($data);
        }else{
            $save = self::create($data);
        }

        if(!$save){
            throw new ServerException('保存失败');
        }
    }

    /**
     * 商家端APP设置的默认信息
     * @param $merch_admin
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function merchAppSetInfo($merch_admin){
        $merch = self::getInfo($merch_admin['merch_id']);
        return [
            'start_hour'=>substr($merch['start_hour'],0,5),
            'end_hour'=>substr($merch['end_hour'],0,5),
        ];
    }

    /**
     * APP端提交设置
     * @param $merch_admin
     * @param $start_hour
     * @param $end_hour
     * @return void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static public function merchAppSetSub($merch_admin,$start_hour,$end_hour){
        $auth = new \MerchAuth();
        if(!$auth->checkMobileApp(1044,$merch_admin['admin_id'])){
            throw new UserException('您没有权限');
        }

        if(strlen($start_hour)==5){
            $start_hour .= ':00';
        }

        if(strlen($end_hour)==5){
            $end_hour .= ':00';
        }

        $data = [
            'id'=>$merch_admin['merch_id'],
            'start_hour'=>$start_hour,
            'end_hour'=>$end_hour
        ];
        self::update($data);

        self::removeCache($merch_admin['merch_id']);

        MerchLog::appRecord($merch_admin['admin_id'],$merch_admin['username'],$merch_admin['merch_id'],'设置服务时间',$data);
    }

    /**
     * 小程序地址
     * @param $id
     * @return string
     */
    static public function getMiniUrl($id,$type){

        if($type==1){
            //团购
            $path = config('self.mini_group_merch_path').$id;
        }else{
            //好物
            $path = config('self.mini_thing_merch_path').$id;
        }

        return $path;
    }

    /**
     * 压缩处理标签
     * @param $tags
     * @return string
     * @throws UserException
     */
    static public function serTags($tags,$name='标签'){
        if(!is_array($tags) || count($tags)<=0){
            return '';
        }

        foreach ($tags as $key=>$item){
            $item = reInject($item);
            if(strpos($item,',')!==false){
                throw new UserException($name.'中请勿使用英文逗号');
            }

            if($item==''){
                unset($tags[$key]);
            }else{
                $tags[$key] = $item;
            }
        }

        $num = config('self.merch_facility_max');

        if(count($tags)>$num){
            throw new UserException('请勿添加超过'.$num.'个'.$name);
        }

        return implode(',',$tags);
    }

    /**
     * 解压标签
     * @param $tags
     * @return array|false|string[]
     */
    static public function unSerTags($tags){
        return $tags=='' ? [] : explode(',',$tags);
    }

    /**
     * 后台添加商家
     * @param $data
     * @return array|void
     * @throws ServerException
     * @throws UserException
     */
    static public function addMerch($data,$people_type,$admin_id)
    {
        unset($data['level']);//后台禁止设置等级
        unset($data['expire_time']);//后台禁止设置等级到期时间

        //验证
        $validate = new \app\common\validate\Merch();
        if(!$validate->check($data)){
            throw new UserException($validate->getError());
        }
//        if (isset($data['expire_time'])&&$data['expire_time']!='') {
//            $data['expire_time'] = strtotime($data['expire_time']);
//        } else {
//            $data['expire_time'] = 0;
//        }

        if($people_type==1){
            //县代 只能初审 添加默认初审通过到待复审
            $data['check'] = 0;
            $data['first_people'] = $admin_id;
            $data['first_time'] = time();
        }elseif($people_type==2){
            //市代 可以复审 添加默认复审通过
            $data['check'] = 1;
            $data['second_type'] = 1;
            $data['second_people'] = $admin_id;
            $data['second_time'] = time();
        }elseif($people_type==3){
            //总平台 可以复审 添加默认复审通过
            $data['check'] = 1;
            $data['second_type'] = 2;
            $data['second_people'] = $admin_id;
            $data['second_time'] = time();
        }

        $add = self::create($data);
        if(!$add){
            throw new ServerException('添加失败');
        }

        //附表标签
        if (isset($data['facility']) && count($data['facility']) > 0) {
            $facility = self::serTags($data['facility']);
            if($facility!=''){
                Db::name('merch_facility')->insert(['merch_id'=>$add->id,'facility'=>$facility]);
            }
        }

        if (isset($data['refund_address'])&&$data['type']==2) {
            Db::name('merch_address')->insert(['merch_id'=>$add->id,'address'=>reInjectThree($data['refund_address'])]);
        }

        //删除商家缓存
        self::removeCache();
    }

    /**
     * 编辑商家
     * @param $data
     * @return array
     * @throws ServerException
     * @throws \think\db\exception\DbException
     */
    public static function editMerch($data)
    {
        unset($data['level']);//后台禁止设置等级
        unset($data['expire_time']);//后台禁止设置等级到期时间

        //验证
        $validate = new \app\common\validate\Merch();
        if(!$validate->check($data)){
            throw new UserException($validate->getError());
        }

        $old = self::field('id,check,type')->find($data['id']);
        if($old['check']==1 && $old['type']!=$data['type']){
            throw new UserException('商家已通过复审，不允许修改类型');
        }

//        if (isset($data['expire_time'])&&$data['expire_time']!='') {
//            $data['expire_time'] = strtotime($data['expire_time']);
//        } else {
//            $data['expire_time'] = 0;
//        }

        $result = self::update($data);
        if (!$result) {
            throw new ServerException('编辑失败');
        }

        //同步积分抵扣比例和会员优惠比例到商品
        if(isset($data['coin_percent'])){
            //商品未开启独立开关则抵扣比例必须同步商家
            Goods::where('merch_id','=',$data['id'])
                ->where('alone_welfare_switch',0)
                ->update(['coin_percent'=>$data['coin_percent']]);

            //商品开启独立开关则抵扣比例必须大于商家默认比例 故小于的要同步到默认比例
            Goods::where('merch_id','=',$data['id'])
                ->where('alone_welfare_switch','=',1)
                ->where('coin_percent','<',$data['coin_percent'])
                ->update(['coin_percent'=>$data['coin_percent']]);
        }

        if(isset($data['vip_percent'])){
            Goods::where('merch_id','=',$data['id'])
                ->where('alone_welfare_switch',0)
                ->update(['vip_percent'=>$data['vip_percent']]);

            Goods::where('merch_id','=',$data['id'])
                ->where('alone_welfare_switch','=',1)
                ->where('vip_percent','<',$data['vip_percent'])
                ->update(['vip_percent'=>$data['vip_percent']]);
        }

        //附表配套
        Db::name('merch_facility')->where('merch_id','=',$data['id'])->delete();
        if (isset($data['facility']) && count($data['facility']) > 0) {
            $facility = self::serTags($data['facility']);
            if($facility!=''){
                Db::name('merch_facility')->insert(['merch_id'=>$data['id'],'facility'=>$facility]);
            }
        }

        //附表退回地址
        Db::name('merch_address')->where('merch_id',$data['id'])->delete();
        if (isset($data['refund_address'])) {
            Db::name('merch_address')->insert(['merch_id'=>$data['id'],'address'=>reInjectThree($data['refund_address'])]);
        }

        //商家信息同步到商品
        $change = [];
        foreach ($data as $k=>$v){
            if(in_array($k,['pro_id','city_id','area_id','longitude','latitude'])){
                $change[$k]=$v;
            }
        }
        if(!empty($change) && !empty($data['id'])){
            Db::name('goods')
                ->where('merch_id',$data['id'])
                ->update($change);
        }

        //删除商家缓存
        self::removeCache($data['id']);
    }

    /**
     * 初审
     * @param $id
     * @param $check
     * @param $reason
     * @param $first_people
     * @return void
     * @throws ServerException
     * @throws UserException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function firstCheck($id,$check,$reason,$first_people){
        $id = intval($id);
        $check = intval($check);
        $reason = reInjectThree($reason);

        $info = self::field('id,uid,check')->find($id);

        if(!$info){
            throw new UserException('无此商家记录');
        }

        if(!in_array($info['check'],[-1])){
            throw new UserException('当前商家审核状态不可初审，请刷新查看当前商家审核状态');
        }

        if(!in_array($check,[-2,0])){
            throw new UserException('选择的审核状态有误');
        }

        if($check==-2 && $reason==''){
            throw new UserException('请输入驳回原因');
        }

        $change = [
            'check'=>$check,
            'reason'=>$reason,
            'first_people'=>$first_people,
            'first_time'=>time()
        ];

        $save = self::where('id',$id)->update($change);
        if(!$save){
            throw new ServerException('保存失败，请稍后再试');
        }

        if($info['uid']&&$check==-2){
            Notice::systemSend(1,$info['uid'],'商家入驻初审驳回提醒','您的商家入驻申请，初审被驳回，请注意查看驳回原因，修改入驻申请后重新提交',4);
        }

        //删除商家缓存
        self::removeCache($id);
    }

    /**
     * 复审
     * @param $id
     * @param $check
     * @param $reason
     * @param $second_type
     * @param $second_people
     * @return void
     * @throws ServerException
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function secondCheck($id,$check,$reason,$second_type,$second_people){
        $id = intval($id);
        $check = intval($check);
        $reason = reInjectThree($reason);

        $info = self::find($id);

        if(!$info){
            throw new UserException('无此商家记录');
        }

        if(!in_array($info['check'],[-1,0])){
            throw new UserException('当前商家审核状态不可复审，请刷新查看当前商家审核状态');
        }

        if(!in_array($check,[1,2])){
            throw new UserException('选择的审核状态有误');
        }

        if($check==2 && $reason==''){
            throw new UserException('请输入驳回原因');
        }

        $change = [
            'check'=>$check,
            'reason'=>$reason,
            'second_type'=>$second_type,
            'second_people'=>$second_people,
            'second_time'=>time()
        ];

        $save = self::where('id',$id)->update($change);
        if(!$save){
            throw new ServerException('保存失败，请稍后再试');
        }

        if($info['uid']){
            if($check==2){
                //复审驳回
                Notice::systemSend(1,$info['uid'],'商家入驻复审驳回提醒','您的商家入驻申请，复审被驳回，请注意查看驳回原因，修改入驻申请后重新提交',4);
            }else{
                Notice::systemSend(1,$info['uid'],'商家入驻审核通过提醒','您的商家入驻申请，复审已审核通过，后续会有客服与您联系，请注意来电',0);
            }
        }

        if($check==1 && $info['business_uid']){
            $business = UserTeamLevel::getBusiness(1,$info['business_uid']);
            if($business){
                Users::where('id',$info['business_uid'])
                    ->inc('recommend_merch',1)
                    ->update();
            }
        }

        //删除商家缓存
        self::removeCache($id);
    }

    /**
     * 删除商家缓存
     * @return void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    static public function removeCache($merch_id=''){
        Cache::store('redis')->delete('zfn_merch');
        if($merch_id){
            Cache::delete('zfn_merch_v1_'.intval($merch_id));
        }

    }

    /**
     * 获取名称
     * @param $merch_id
     * @return mixed
     */
    static public function getTitle($merch_id){

        $info = self::getInfo($merch_id);
        if($info){
            return $info['title'];
        }else{
            return '';
        }
    }

    /**
     * 获取商家信息不包含随时变动的信息 如 等级、等级过期时间、余额、累计余额等
     * @param $merch_id
     * @return array|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function getInfo($merch_id){
        $merch_id = intval($merch_id);
        $info = Db::name('merch')
            ->where('id',$merch_id)
            ->withoutField('level,expire_time,money,money_history,views,views_show,update_time')
            ->cache('zfn_merch_v1_'.$merch_id,36000)
            ->find();
//        $info = !$info ? '' : $info;
        return $info;
    }

    /**
     * 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function getList($type=0,$city_id=0,$area_id=0): array
    {

        $cache_name = 'zfn_merch';
        $expire = 86400;
        $data = Cache::store('redis')->remember($cache_name, function () {
            return self::where('check',1)
                ->order('id DESC')
                ->column('id,type,title,pro_id,city_id,area_id','id');
        }, $expire);

        //根据条件 返回符合的商家
        if($type || $city_id || $area_id){

            foreach ($data as $key=>$item){
                if($type && $item['type'] != $type){
                    unset($data[$key]);
                }

                if($city_id && $item['city_id'] != $city_id){
                    unset($data[$key]);
                }

                if($area_id && $item['area_id'] != $area_id){
                    unset($data[$key]);
                }
            }

        }

        return $data;
    }
}